from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Dict, Any
import uuid
from database import get_db
from model.models import ToolConfig, ToolCategory
from module.agent_manager import reload_agent

router = APIRouter(prefix="/api/tool-config", tags=["Tool Config"])

@router.get("", response_model=List[Dict[str, Any]])
def get_tools(db: Session = Depends(get_db)):
    tools = db.query(ToolConfig).order_by(ToolConfig.category, ToolConfig.sort_order).all()
    return [t.to_dict() for t in tools]

@router.post("", response_model=Dict[str, Any])
def create_tool(tool: Dict[str, Any], db: Session = Depends(get_db)):
    if not tool.get("key") or not tool.get("name") or not tool.get("category"):
        raise HTTPException(status_code=400, detail="key、name、category不能为空")
    
    existing = db.query(ToolConfig).filter(ToolConfig.key == tool.get("key")).first()
    if existing:
        raise HTTPException(status_code=400, detail="该key已存在")
    
    new_tool = ToolConfig(
        id=str(uuid.uuid4()),
        key=tool.get("key"),
        name=tool.get("name"),
        description=tool.get("description", ""),
        category=tool.get("category"),
        is_enabled=tool.get("is_enabled", True),
        sort_order=tool.get("sort_order", 0)
    )
    db.add(new_tool)
    db.commit()
    db.refresh(new_tool)
    return new_tool.to_dict()

@router.put("/{tool_id}", response_model=Dict[str, Any])
def update_tool(tool_id: str, tool: Dict[str, Any], db: Session = Depends(get_db)):
    db_tool = db.query(ToolConfig).filter(ToolConfig.id == tool_id).first()
    if not db_tool:
        raise HTTPException(status_code=404, detail="工具不存在")
    
    if tool.get("key") and tool.get("key") != db_tool.key:
        existing = db.query(ToolConfig).filter(ToolConfig.key == tool.get("key")).first()
        if existing:
            raise HTTPException(status_code=400, detail="该key已存在")
    
    is_enabled_changed = "is_enabled" in tool and tool.get("is_enabled") != db_tool.is_enabled
    
    for key, value in tool.items():
        if hasattr(db_tool, key):
            setattr(db_tool, key, value)
    
    db.commit()
    db.refresh(db_tool)
    
    if is_enabled_changed:
        reload_agent()
    
    return db_tool.to_dict()

@router.delete("/{tool_id}")
def delete_tool(tool_id: str, db: Session = Depends(get_db)):
    db_tool = db.query(ToolConfig).filter(ToolConfig.id == tool_id).first()
    if not db_tool:
        raise HTTPException(status_code=404, detail="工具不存在")
    
    db.delete(db_tool)
    db.commit()
    return {"message": "删除成功"}

@router.get("/categories")
def get_categories(db: Session = Depends(get_db)):
    categories = db.query(ToolCategory).order_by(ToolCategory.sort_order).all()
    return [c.to_dict() for c in categories]

@router.post("/categories", response_model=Dict[str, Any])
def create_category(category: Dict[str, Any], db: Session = Depends(get_db)):
    if not category.get("name"):
        raise HTTPException(status_code=400, detail="分类名称不能为空")
    
    existing = db.query(ToolCategory).filter(ToolCategory.name == category.get("name")).first()
    if existing:
        raise HTTPException(status_code=400, detail="该分类已存在")
    
    new_category = ToolCategory(
        id=str(uuid.uuid4()),
        name=category.get("name"),
        description=category.get("description", ""),
        sort_order=category.get("sort_order", 0)
    )
    db.add(new_category)
    db.commit()
    db.refresh(new_category)
    return new_category.to_dict()

@router.put("/categories/{category_id}", response_model=Dict[str, Any])
def update_category(category_id: str, category: Dict[str, Any], db: Session = Depends(get_db)):
    db_category = db.query(ToolCategory).filter(ToolCategory.id == category_id).first()
    if not db_category:
        raise HTTPException(status_code=404, detail="分类不存在")
    
    if category.get("name") and category.get("name") != db_category.name:
        existing = db.query(ToolCategory).filter(ToolCategory.name == category.get("name")).first()
        if existing:
            raise HTTPException(status_code=400, detail="该分类名称已存在")
    
    for key, value in category.items():
        if hasattr(db_category, key):
            setattr(db_category, key, value)
    
    db.commit()
    db.refresh(db_category)
    return db_category.to_dict()

@router.delete("/categories/{category_id}")
def delete_category(category_id: str, db: Session = Depends(get_db)):
    db_category = db.query(ToolCategory).filter(ToolCategory.id == category_id).first()
    if not db_category:
        raise HTTPException(status_code=404, detail="分类不存在")
    
    tools_count = db.query(ToolConfig).filter(ToolConfig.category == db_category.name).count()
    if tools_count > 0:
        raise HTTPException(status_code=400, detail=f"该分类下还有{tools_count}个工具，无法删除")
    
    db.delete(db_category)
    db.commit()
    return {"message": "删除成功"}
